import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter App',
      theme: ThemeData(primarySwatch: Colors.red),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final GlobalKey _globalKey1 = GlobalKey();
  final GlobalKey _globalKey2 = GlobalKey();
  final GlobalKey _globalKey3 = GlobalKey();

  List<Widget> list = [
    const Box(key: ValueKey("1"), color: Colors.red),
    Box(key: UniqueKey(), color: Colors.yellow), // UniqueKey 是唯一值 随机生成
    const Box(
      key: ObjectKey(Box(color: Colors.blue)),
      color: Colors.blue,
    ),
  ];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    list = [
      Box(key: _globalKey1, color: Colors.red),
      Box(key: _globalKey2, color: Colors.blue), // UniqueKey 是唯一值 随机生成
      Box(key: _globalKey3, color: Colors.orange),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.refresh),
        onPressed: () {
          setState(() {
            list.shuffle(); // 随机排序
          });
        },
      ),
      appBar: AppBar(
        title: const Text('FloatingActionButton'),
        backgroundColor: Colors.teal,
      ),
      body: Center(child: Column(children: list)),
    );
  }
}

class Box extends StatefulWidget {
  final Color color;
  const Box({super.key, required this.color});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 100,
      height: 100,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: WidgetStateProperty.all(widget.color),
        ),
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        child: Text('$_count', style: Theme.of(context).textTheme.displayLarge),
      ),
    );
  }
}
